const state = {
  newsList: [],
  newsIndex: [],
  page: 1,
  catId: 0,
  setPage: 1,
  url: process.env.VUE_APP_newsList_url,
  indexList: {}
}

const mutations = {
  setNewsList (state, list) {
    state.newsList = state.newsList.concat(list)
  },
  resetNewsList (state, catId) {
    state.newsList = []
    state.catId = catId
    state.page = 1
  },
  addPage (state) {
    state.page++
  },
  setPage (state, setPage) {
    state.setPage = setPage
  },
  modifyNewsIndex (state, param) {
    state.newsIndex = param.concat()
  },
  setNewsIndex (state, param) {
    let data = Object.assign({}, state.newsIndex[param.index])
    data.page = param.data.page
    data.list = param.data.list
    state.newsIndex.splice(param.index, 1, data)
  }
}

const actions = {
  setNewsList ({ commit, state }, param) {
    let catId = param.catId
    let limit = param.limit || 5
    if (state.catId != catId) {
      commit('resetNewsList', catId)
      commit('setPage', 1)
    }
    window.axios.post(state.url, {
      cat_id: state.catId,
      page: state.page,
      limit: limit
    }).then(ret => {
      if (ret.data.length > 0) {
        commit('setNewsList', ret.data)
        commit('setPage', ret.data.length)
        commit('addPage')
      } else {
        commit('setPage', ret.data.length)
      }
    }).catch(() => { })
  },
  setNewsIndex ({ commit, state }, param = {}) {
    let catList = state.newsIndex
    // console.log(catList)
    for (let [index, item] of catList.entries()) {
      setTimeout(function () {
        window.axios.post(state.url, {
          cat_id: item.id,
          page: 1,
          limit: param.page || 10
        }).then(ret => {
          if (ret.data.length > 0) {
            commit('setNewsIndex', { index: index, data: { page: 1, list: ret.data } })
          }
        }).catch(() => { })
      }, index * 300)
    }
  },
  newsIndexChange ({ commit, state }, index) {
    let data = Object.assign({}, state.newsIndex[index])
    if (data != undefined) {
      window.axios.post(state.url, {
        cat_id: data.id,
        page: ++data.page,
        limit: 10
      }).then(ret => {
        if (ret.data.length > 0) {
          commit('setNewsIndex', { index: index, data: { page: data.page, list: ret.data } })
        }
      }).catch(() => { })
    }
  },
  setIndexList ({ commit, state }, index) {
    let a = state.indexList[index]
    console.log(a)

  }
}

export default {
  state,
  mutations,
  actions
}